package com.unirio.pm.rules;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.unirio.pm.interfaces.PasswordRule;

public class RegexFrequencyChecker implements PasswordRule {

	private String description;
	private String regex;
	private int score;
	private int parameter;
	private String scoreRegex;
	private boolean size;

	public RegexFrequencyChecker(String regex, int parameter, String scoreRegex, boolean size){
		this.description = "";
		this.regex = regex;
		this.scoreRegex = scoreRegex;
		this.parameter = parameter;
		this.size = size;
	}

	public RegexFrequencyChecker(String description, String regex, int parameter, String scoreRegex, boolean size) {
		this.description = description;
		this.regex = regex;
		this.scoreRegex = scoreRegex;
		this.parameter = parameter;
		this.size = size;
	}

	public RegexFrequencyChecker(String regex, int parameter) {
		this.regex = regex;
		this.parameter = parameter;
	}

	public int checkRule(String password) {
		int score = 0;
		if(this.scoreRegex==null) {
			Pattern pattern = Pattern.compile(this.regex);
			Matcher matcher = pattern.matcher(password);
			while (matcher.find()) {
				score++;
			}
			return -(score*this.parameter);
		}
		int count = checkFrequency(password, this.regex);
		if(this.size) {
			if(count > 0 && count >= password.length()) {
				return score;
			}
		}
		if(count > 0) {
			score = checkFrequency(password, this.scoreRegex)*this.parameter;
		}
		return score;
	}

	public int checkFrequency(String password, String regex) {
		return password.replaceAll(regex, "").length();
	}

}

